package com.ihomey.linkuphome.ui;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.ihomey.cc.library.util.FileUtil;
import com.ihomey.linkuphome.DeviceController;
import com.ihomey.linkuphome.R;
import com.ihomey.linkuphome.app.Constant;
import com.ihomey.linkuphome.base.BaseFragment;
import com.ihomey.linkuphome.util.Auth;
import com.ihomey.linkuphome.util.BindView;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

/**
 * Created by Administrator on 2017/6/10 0010.
 */

public class ControlShareFragment extends BaseFragment implements View.OnClickListener {

    @BindView(id = R.id.iv_qrCode)
    private ImageView iv_qrCode;
    @BindView(id = R.id.tv_qrCodeGenerate_result)
    private TextView tv_qrCodeGenerate_result;
    @BindView(id = R.id.tv_qrCode_generate, click = true)
    private TextView tv_qrCode_generate;
    @BindView(id = R.id.tv_qrCode_save, click = true)
    private TextView tv_qrCode_save;


    @BindView(id = R.id.tv_shareQRTips)
    private TextView tv_shareQRTips;
    @BindView(id = R.id.tv_shareQR)
    private TextView tv_shareQR;
    @BindView(id = R.id.tv_downloadAppTips)
    private TextView tv_downloadAppTips;
    @BindView(id = R.id.tv_openAppScanTips)
    private TextView tv_openAppScanTips;
    @BindView(id = R.id.tv_shareSuccessTips)
    private TextView tv_shareSuccessTips;


    private MainActivity mainActivity;
    private DeviceController mController;
    private Bitmap bitmap = null;


    public static ControlShareFragment newInstance() {
        ControlShareFragment fragment = new ControlShareFragment();
        return fragment;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.activity_contro_share, null);
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mainActivity = (MainActivity) activity;
            mController = (DeviceController) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement DeviceController callback interface.");
        }
    }


    @Override
    public void initWidget(View parentView) {
        super.initWidget(parentView);

        mainActivity.setTitle(R.string.qrCode);
        mainActivity.showRightBtn(false);

        if (mainActivity.getLanguage().equals("zh")) {
            tv_shareQRTips.setTextSize(14);
            tv_downloadAppTips.setTextSize(12);
            tv_openAppScanTips.setTextSize(12);
            tv_shareSuccessTips.setTextSize(12);
            tv_qrCodeGenerate_result.setTextSize(16);
            tv_qrCode_generate.setTextSize(16);
            tv_qrCode_save.setTextSize(16);
            tv_shareQR.setTextSize(16);
        } else {
            tv_qrCodeGenerate_result.setTextSize(14);
            tv_shareQRTips.setTextSize(10);
            tv_downloadAppTips.setTextSize(8);
            tv_openAppScanTips.setTextSize(8);
            tv_shareSuccessTips.setTextSize(8);
            tv_qrCode_generate.setTextSize(14);
            tv_qrCode_save.setTextSize(14);
            tv_shareQR.setTextSize(14);
        }
    }

    @Override
    public void initData() {
        super.initData();
        createQRCode();
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_qrCode_generate) {
            createQRCode();
        } else if (view.getId() == R.id.tv_qrCode_save && bitmap != null) {
//            if (bitmap == null) {
//                Toast.makeText(this, "尚未生成数据共享二维码！", Toast.LENGTH_SHORT).show();
//            } else {
            FileUtil.saveImageToGallery(getActivity(), bitmap, "ihomey/img");
//            }
        }
    }


    private void createQRCode() {
        try {
            String dataBaseJson = mController.getDataBaseAsJson();
            Log.d("aa", dataBaseJson);
            String configuration = URLEncoder.encode(dataBaseJson, "UTF-8").replace("+", "%20");
            if (!TextUtils.isEmpty(configuration)) {
                String ACCESS_KEY = Constant.ACCESS_KEY;
                String SECRET_KEY = Constant.SECRET_KEY;
                String BUCKET_NAME = Constant.BUCKET_NAME;
                String key = "IHomey_" + System.currentTimeMillis() + ".json";
                Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
                Configuration config = new Configuration.Builder().build();
                UploadManager uploadManager = new UploadManager(config);
                mainActivity.showProgressDialog("正在生成数据共享二维码...");
                uploadManager.put(configuration.getBytes(), key, auth.uploadToken(BUCKET_NAME), new UpCompletionHandler() {
                    @Override
                    public void complete(final String key, ResponseInfo info, JSONObject response) {
                        if (info.isOK()) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    bitmap = QRCodeEncoder.syncEncodeQRCode(Constant.DOMAIN + key, BGAQRCodeUtil.dp2px(getActivity(), 215));
                                    mainActivity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            mainActivity.hideProgressDialog();
                                            iv_qrCode.setImageBitmap(bitmap);
                                            tv_qrCodeGenerate_result.setVisibility(View.VISIBLE);
                                            tv_qrCodeGenerate_result.setText(R.string.qrCode_generate_done);
                                        }
                                    });
                                }
                            }).start();

                        } else {
                            mainActivity.hideProgressDialog();
                            tv_qrCodeGenerate_result.setVisibility(View.VISIBLE);
                            tv_qrCodeGenerate_result.setText(R.string.qrCode_generate_fail);
                        }
                    }
                }, null);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
